from flask_restx import Resource
from flask import request
from api import ns
from models.database import get_db_connection
from services.baidu_service import BaiduAIService
from utils.auth import token_required
import traceback
import uuid
from datetime import datetime

# 创建一个全局的 BaiduAIService 实例
baidu_service = BaiduAIService()

@ns.route('/generate')
class EmojiGenerator(Resource):
    @token_required
    def post(self):
        """生成表情包"""
        try:
            data = request.get_json()
            if not data:
                return {'status': 'error', 'message': '无效的请求数据'}, 400
            
            # 验证必填字段
            required_fields = ['text', 'style']
            for field in required_fields:
                if not data.get(field):
                    return {'status': 'error', 'message': f'{field} 不能为空'}, 400
            
            # 获取用户ID
            user_id = request.user.get('user_id')
            
            # 调用百度AI生成表情包
            print("Calling Baidu API with:", data)
            result = baidu_service.generate_emoji(
                text=data['text'],
                style=data['style']
            )
            print("Baidu API response:", result)
            
            # 检查生成结果
            if not result['success']:
                print(f"Generation failed: {result['error_msg']}")
                return {
                    'status': 'error',
                    'message': result['error_msg']
                }, 500
            
            # 保存生成记录
            conn = get_db_connection()
            cursor = conn.cursor()
            
            try:
                # 生成UUID作为history_id
                history_id = str(uuid.uuid4())
                print(f"Generated history_id: {history_id}")
                
                # 打印插入数据
                insert_data = (
                    history_id,
                    user_id,
                    data['text'],
                    data['style'],
                    result['image_url']
                )
                print("Inserting data:", insert_data)
                
                cursor.execute("""
                    INSERT INTO history (
                        history_id, user_id, prompt_text, style, 
                        output_url, created_at, likes, downloads,
                        is_dynamic, animation_type
                    ) VALUES (
                        %s, %s, %s, %s, %s, NOW(), 0, 0, 0, NULL
                    )
                """, insert_data)
                
                conn.commit()
                print("Record inserted successfully")
                
                return {
                    'status': 'success',
                    'data': {
                        'history_id': history_id,
                        'image_url': result['image_url'],
                        'text': data['text'],
                        'style': data['style']
                    }
                }
                
            except Exception as e:
                conn.rollback()
                print(f"Database error: {str(e)}")
                print("Error details:", traceback.format_exc())
                return {
                    'status': 'error',
                    'message': '保存记录失败',
                    'detail': str(e)
                }, 500
                
            finally:
                if conn:
                    conn.close()
                    
        except Exception as e:
            print(f"Generation error: {str(e)}")
            print("Error details:", traceback.format_exc())
            return {
                'status': 'error',
                'message': str(e)
            }, 500

@ns.route('/generate/status/<task_id>')
class GenerationStatus(Resource):
    @token_required
    def get(self, task_id):
        """检查生成状态"""
        try:
            print(f"Checking status for task: {task_id}")
            result = baidu_service.check_generation_status(task_id)
            print("Status check result:", result)
            
            if result['success'] and result['status'] == 'completed':
                # 如果生成完成，保存记录
                user_id = request.user.get('user_id')
                conn = get_db_connection()
                cursor = conn.cursor()
                
                try:
                    # 生成UUID作为history_id
                    history_id = str(uuid.uuid4())
                    print(f"Generated history_id: {history_id}")
                    
                    # 使用正确的表名和字段名
                    cursor.execute("""
                        INSERT INTO history (
                            history_id, user_id, prompt_text, style, 
                            output_url, created_at, likes, downloads,
                            is_dynamic, animation_type
                        ) VALUES (
                            %s, %s, %s, %s, %s, NOW(), 0, 0, 0, NULL
                        )
                    """, (
                        history_id,
                        user_id,
                        request.args.get('text'),
                        request.args.get('style'),
                        result['image_url']
                    ))
                    
                    conn.commit()
                    result['history_id'] = history_id
                    print("Record inserted successfully")
                    
                except Exception as e:
                    conn.rollback()
                    print(f"Database error: {str(e)}")
                    print("Error details:", traceback.format_exc())
                finally:
                    if conn:
                        conn.close()
            
            return result
            
        except Exception as e:
            print(f"Check status error: {str(e)}")
            print("Error details:", traceback.format_exc())
            return {
                'success': False,
                'message': str(e)
            }, 500